<script setup lang="ts">
import { reactive, onMounted, ref, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useEmitt } from '@/hooks/web/useEmitt'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { useLocaleStore } from '@/store/modules/locale'
import { SerialNoDialog, EntityDialog, DictSelectDialog } from '@/components/Dialog'
import { getZhHKAndPinyin, getZhCNAndPinyin } from '@/api/common'
import { selectModule, selectDataSource } from '@/api/develop'
import {
  saveEntity,
  publishEnt,
  getEntity,
  checkTableName,
  getFixedCols,
  getDataTypes
} from '@/api/develop/entity'

defineOptions({
  name: 'EntityAdd'
})

const localeStore = useLocaleStore()

const { t } = useI18n()
const { emitter } = useEmitt()
const formRef = ref()
const { currentRoute } = useRouter()

//默认的索引对象
const defautIndex = {
  id: null,
  entId: null,
  fields: [],
  indexName: '',
  isUnique: 0,
  status: 0,
  seq: 1
}
const state = reactive({
  // 表单数据
  formData: {
    entId: undefined,
    entName: '',
    hkName: '',
    enName: '',
    moduleId: '',
    tableName: '',
    dsId: '',
    remark: '',
    status: 0,
    isBuildIn: 0,
    isGenDb: 1,
    isLogicDel: 1,
    isFromDb: 0,
    genLog: 0,
    createTime: null,
    createBy: '',
    updateTime: null,
    updateBy: '',
    seq: 1,
    cols: [{}],
    indexes: [{}]
  },
  deleteIds: [{}],

  // 校验规则
  formRules: {
    tableName: [
      {
        required: true,
        pattern: /^[a-z]{1}[a-z0-9_]{0,}$/,
        message: t('entity.colNameCheck'),
        trigger: ['blur']
      }
    ],
    entName: {
      required: true,
      message: t('entity.name') + t('common.notEmpty'),
      trigger: ['blur']
    },
    moduleId: [
      {
        required: true,
        message: t('orderNo.module') + t('common.notEmpty'),
        trigger: ['blur', 'change']
      }
    ]
  },
  dialogVisible: false,
  serialNoDialogVisible: false,
  entityDialogVisible: false,
  dictSelectDialogVisible: false,
  dialogForm: { ...defautIndex },
  dialogRule: {
    fields: {
      required: true,
      message: t('entity.fields') + t('common.notEmpty'),
      trigger: ['blur']
    }
  },
  modNameField: 'moduleName',
  colNameField: 'showName',
  entityNameField: 'refEntName',
  orderNoField: 'refOrderName',
  dictNameField: 'dictName',
  moduleList: [{}],
  dsList: [{}],
  logOptions: [
    { id: 1, name: t('common.add') },
    { id: 2, name: t('common.modify') },
    { id: 4, name: t('common.delete') }
  ],
  logValues: [],
  dataTypes: [{}],
  controlTypes: [
    { value: 'input', label: t('controlType.input') },
    { value: 'textarea', label: t('controlType.textarea') },
    { value: 'number', label: t('controlType.number') },
    { value: 'switch', label: t('controlType.switch') },
    { value: 'date', label: t('controlType.date') },
    { value: 'datetime', label: t('controlType.datetime') },
    { value: 'time', label: t('controlType.time') },
    { value: 'select', label: t('controlType.select') },
    { value: 'radio', label: t('controlType.radio') },
    { value: 'checkbox', label: t('controlType.checkbox') },
    { value: 'refEntity', label: t('controlType.refEntity') },
    { value: 'orderNo', label: t('controlType.orderNo') },
    { value: 'dictionary', label: t('controlType.dictionary') },
    { value: 'person', label: t('controlType.person') },
    { value: 'userGroup', label: t('controlType.userGroup') },
    { value: 'upload', label: t('controlType.upload') },
    { value: 'rate', label: t('controlType.rate') },
    { value: 'color', label: t('controlType.color') }
  ],
  curRow: {} as any,
  loading: false,
  publishLoading: false,
  fromPath: ''
})

//加载事件
onMounted(async () => {
  state.moduleList = await selectModule()
  state.dataTypes = await getDataTypes()
  //当前语言
  const curLang = localeStore.getCurrentLocale.lang
  if (curLang == 'en') {
    state.modNameField = 'enName'
    state.colNameField = 'enName'
    state.entityNameField = 'refEnName'
    state.orderNoField = 'refEnOrderName'
    state.dictNameField = 'dictEnName'
  } else if (curLang == 'zh_HK') {
    state.modNameField = 'hkName'
    state.colNameField = 'hkName'
    state.entityNameField = 'refHkName'
    state.orderNoField = 'refHkOrderName'
    state.dictNameField = 'dictHkName'
  }
  init()
})

//根据模块变化刷新数据源
const refreshDsList = async (event) => {
  const moduleId = event
  if (!moduleId || moduleId.length == 0) {
    return
  }
  state.dsList = (await selectDataSource(moduleId)).data
  formRef.value.clearValidate(['dsId'])
  //校验数据源ID
  if (state.formData.dsId) {
    if (!containDsId(state.dsList, state.formData.dsId)) {
      state.formData.dsId = ''
    }
  }
}

//双击选择数据字典
const dblClickSelectDict = (row) => {
  state.curRow = row
  state.dictSelectDialogVisible = true
}

//字段选择数据字典
const selectDict = (data) => {
  state.curRow.dictId = data.pkId
  state.curRow.dictName = data.dicName
  state.curRow.dictHkName = data.hkName
  state.curRow.dictEnName = data.enName
  state.dictSelectDialogVisible = false
  state.curRow.controlType = 'dictionary'
}

//清空当前行数据字典
const clearDict = (row) => {
  row.dictId = ''
  row.dictName = ''
  row.dictEnName = ''
  row.dictHkName = ''
  row.controlType = 'input'
}

//选择单据编号字段配置
const selectNo = (data) => {
  state.curRow.refSerialNo = data.pkId
  state.curRow.refOrderName = data.orderName
  state.curRow.refHkOrderName = data.hkName
  state.curRow.refEnOrderName = data.enName
  state.curRow.isReadonly = 1
  state.serialNoDialogVisible = false
  state.curRow.controlType = 'orderNo'
}

//双击选择单号
const dblClickSelectNo = (row) => {
  state.curRow = row
  state.serialNoDialogVisible = true
}
//清空当前行单号
const clearNo = (row) => {
  row.refSerialNo = ''
  row.refOrderName = ''
  row.refHkOrderName = ''
  row.refEnOrderName = ''
  row.isReadonly = 0
  row.controlType = 'input'
}

//选择字段引用实体
const selectRefEnt = (data) => {
  state.curRow.refEntId = data.pkId
  state.curRow.refEntName = data.entName
  state.curRow.refHkName = data.hkName
  state.curRow.refEnName = data.enName
  state.entityDialogVisible = false
  state.curRow.controlType = 'refEntity'
  state.curRow.colType = 'varchar'
  state.curRow.colLength = 64
}

//双击选择引用实体
const dblClickSelectEnt = (row) => {
  state.curRow = row
  state.entityDialogVisible = true
}

//清空当前行引用实体
const clearEnt = (row) => {
  row.refEntId = ''
  row.refEntName = ''
  row.refEnName = ''
  row.refHkName = ''
  row.controlType = 'input'
}

//检查列表中是否包含当前数据源ID
const containDsId = (dsList, dsId) => {
  if (!dsList || !dsId) {
    return false
  }
  for (let ds of dsList) {
    if (ds.dsId == dsId) {
      return true
    }
  }
  return false
}
//数据类型改变事件
const changDataType = async (row) => {
  await nextTick()
  row.colPrec = 0
  if (row.colType == 'varchar') {
    row.colLength = 50
  } else if (row.colType == 'decimal') {
    row.colLength = 18
    row.colPrec = 2
  } else {
    row.colLength = 1
  }
  //默认控件类型
  if (row.colType == 'text' || row.colType == 'longtext') {
    row.controlType = 'textarea'
  } else if (row.colType == 'date') {
    row.controlType = 'date'
  } else if (row.colType == 'datetime') {
    row.controlType = 'datetime'
  } else {
    row.controlType = 'input'
  }
}

//控件类型改变
const controlTypeChange = async (row) => {
  await nextTick()
  if (row.controlType == 'refEntity') {
    dblClickSelectEnt(row)
  } else if (row.controlType == 'orderNo') {
    dblClickSelectNo(row)
  } else if (row.controlType == 'dictionary') {
    dblClickSelectDict(row)
  }
}

//删除表字段
const deleteRow = (row) => {
  const id = row.colId
  if (id && id.length > 0) {
    state.deleteIds.push(id)
  }
  const index = getRowIndex(row.fieldName)
  console.log('删除字段：' + row.fieldName + '@' + index)
  state.formData.cols.splice(index, 1)
}
//定位要删除字段行的下标
const getRowIndex = (fieldName) => {
  const length = state.formData.cols.length
  for (let i = 0; i < length; i++) {
    const col = state.formData.cols[i] as any
    if (col.fieldName == fieldName) {
      return i
    }
  }
  return -1
}

//新增默认字段
const addRow = () => {
  const newIndex = state.formData.cols.length + 1
  let row = {
    colId: null,
    fieldName: 'field_' + newIndex,
    showName: '',
    hkName: '',
    enName: '',
    colType: 'varchar',
    controlType: 'input',
    colLength: 50,
    colPrec: 0,
    defaultVal: '',
    isUnique: 0,
    isRequired: 0,
    colOrder: newIndex,
    isHide: 0,
    isPk: 0,
    refEntId: null,
    mainCol: 0,
    canSearch: 0,
    others: '',
    remark: '',
    isBuildIn: 0,
    seq: 1
  }
  state.formData.cols.push(row)
  return row
}

//新增固定字段
const addFixedRow = async () => {
  let cols = await getFixedCols()
  for (var col of cols) {
    state.formData.cols.push(col)
  }
}

//批量增加5行
const addFiveRow = () => {
  for (var i = 0; i < 5; i++) {
    addRow()
  }
}
//发布实体
const publish = async () => {
  let tips = t('entity.publishTip2')
  if (state.formData.isGenDb == 1) {
    tips = t('entity.publishTip1') + tips
  }
  ElMessageBox.confirm(tips, t('entity.confirm'), {
    type: 'warning'
  }).then(() => {
    state.publishLoading = true
    publishEnt(state.formData.entId).then((res) => {
      const result = res as any
      state.publishLoading = false
      if (!res) {
        return
      }
      //发布成功
      if (result.success) {
        //刷新列表
        emitter.emit('refreshEntityList', 'edit')
        if (result.message != 'entity.manually') {
          ElMessage.success(t(result.message))
          goBack()
          return
        }
        //物理表有记录，显示待执行的SQL
        const sqls = result.data as Array<string>
        const msg = sqls.join(';\r\n') + ';'
        const html =
          '<strong>' +
          t(result.message) +
          '</strong><br/><br/>' +
          '<textarea rows=8 style="width:568px;border:1px solid #ddd;padding:5px">' +
          msg +
          '</textarea>'
        ElMessageBox.alert(html, '', {
          dangerouslyUseHTMLString: true,
          customStyle: { height: '370px', width: '600px' }
        })
      }
    })
  })
}
// 保存实体
const save = () => {
  formRef.value.validate(async (vaild) => {
    if (!vaild) {
      return
    }
    let form = Object.assign({}, state.formData)
    //校验明细记录
    if (!state.formData.cols || state.formData.cols.length == 0) {
      ElMessage.warning(t('entity.noFields'))
      return
    }
    for (let row2 of state.formData.cols) {
      const row = row2 as any
      if (row.showName == '' || row.fieldName == '' || row.colType == '') {
        ElMessage.warning(t('dataDict.rowCheck'))
        return
      }
    }
    if (checkDetails()) {
      return
    }
    let deleteIds = ''
    if (state.deleteIds && state.deleteIds.length > 0) {
      deleteIds = state.deleteIds.join(',')
    }
    //将日志选项值累加到一个字段中
    let genLog = 0
    for (const a of state.logValues) {
      genLog += a
    }
    form.genLog = genLog
    let data = { entity: form, deleteIds: deleteIds }
    state.loading = true
    let type = 'add'
    if (form.entId) {
      type = 'edit'
    }
    await saveEntity(data).then((res) => {
      const result = res as any
      state.loading = false
      if (!res) {
        return
      }
      //保存成功
      if (result.success) {
        //刷新列表
        emitter.emit('refreshEntityList', type)
        ElMessage.success(t('group.saveSuccess'))
        if (!state.formData.entId) {
          goBack()
        }
        state.formData.seq += 1
      }
    })
  })
}

//检查子表关键列是否有重复
const checkDetails = () => {
  if (state.formData.cols.length == 0) {
    return false
  }
  const len = state.formData.cols.length
  const fNames = new Set()
  for (const detail of state.formData.cols) {
    const row = detail as any
    fNames.add(row.fieldName)
  }
  if (fNames.size != len) {
    ElMessage.error(t('entity.fNameRepeat'))
    return true
  }
  return false
}

//检查TableName是否重复
const checkName = (event) => {
  const key = event.target.value
  if (!key || key.length == 0) {
    return
  }
  checkTableName(key, state.formData.entId, state.formData.dsId)
}
// 返回列表
const goBack = () => {
  emitter.emit('closeTag', {
    closePath: currentRoute.value.fullPath,
    backPath: state.fromPath
  })
}

//创建索引
const addIndex = () => {
  const fields = state.dialogForm.fields
  if (!fields) {
    ElMessage.warning(t('entity.indexTip'))
    return
  }
  const newName = 'idx_' + state.formData.tableName + '_' + fields.join('_')
  if (state.formData.indexes && state.formData.indexes.length > 0) {
    //检查是否有重名
    for (const i of state.formData.indexes) {
      if (i['indexName'] == newName) {
        ElMessage.warning(t('entity.addIndexTip'))
        return
      }
    }
  }
  let index = { ...state.dialogForm }
  index.fields = fields.join(',') as any
  index.indexName = newName
  state.formData.indexes.push(index)
  state.dialogForm = { ...defautIndex }
}

//删除索引
const delIndex = (row) => {
  //未保存的直接删除
  if (!row.id) {
    const index = getIndexIndex(row.indexName)
    console.log('删除索引：' + row.indexName + '@' + index)
    state.formData.indexes.splice(index, 1)
  } else {
    //已保存的改状态
    row.status = 4
  }
}

//定位要删除索引下标
const getIndexIndex = (indexName) => {
  const length = state.formData.indexes.length
  for (let i = 0; i < length; i++) {
    const col = state.formData.indexes[i] as any
    if (col.indexName == indexName) {
      return i
    }
  }
  return -1
}
//可以索引的字段，排除主键
const getIndexFields = () => {
  const fields = state.formData.cols
  if (!fields || fields.length == 0) {
    return []
  }
  var newFields = []
  for (const row of fields) {
    if (row['fieldName'] != 'id') {
      const newRow = { label: row[state.colNameField], value: row['fieldName'] }
      newFields.push(newRow as never)
    }
  }
  return newFields
}
/**
 * @description 当繁体中文为空时，转换简体中文为繁体中文
 * @author Elwin ZHANG
 * @date 2023-03-21 10:33
 */
const zhHKAndPinyin = async (event) => {
  const text = event.target.value
  if (!text || text.length == 0) {
    return
  }
  //繁体中文为空时才自动转换
  if (state.formData.hkName.length > 0) {
    return
  }
  let data = (await getZhHKAndPinyin(text, 50)) as any
  state.formData.hkName = data.data.zhHK
  //如果英文字段为空，默认为拼音
  if (state.formData.enName.length == 0) {
    state.formData.enName = data.data.pinyin
  }
  if (state.formData.tableName.length == 0) {
    state.formData.tableName = 't_' + state.formData.enName.replaceAll(' ', '_')
  }
  formRef.value.clearValidate(['entName', 'tableName'])
}

/**
 * 子表输入简体中文后的事件
 * @param event 事件
 * @param row 当前行记录
 */
const inputCnText = async (event, row) => {
  const text = event.target.value
  if (!text || text.length == 0) {
    return
  }
  if (row.hkName.length > 0) {
    return
  }
  let data = (await getZhHKAndPinyin(text, 50)) as any
  row.hkName = data.data.zhHK
  //如果英文字段为空，默认为拼音
  if (row.enName.length == 0) {
    row.enName = data.data.pinyin
  }
}

/**
 * 子表输入繁体中文后的事件
 * @param event 事件
 * @param row 当前行记录
 */
const inputHkText = async (event, row) => {
  const text = event.target.value
  if (!text || text.length == 0) {
    return
  }
  if (row.showName.length > 0) {
    return
  }
  let data = (await getZhCNAndPinyin(text, 50)) as any
  row.showName = data.data.zhCN
  //如果英文字段为空，默认为拼音
  if (row.enName.length == 0) {
    row.enName = data.data.pinyin
  }
}

/**
 * @description 当简体中文为空时，转换繁体中文为简体中文
 * @author Elwin ZHANG
 * @date 2023-03-21 10:33
 */
const zhCNAndPinyin = async (event) => {
  const text = event.target.value
  if (!text || text.length == 0) {
    return
  }
  //简体中文为空时才自动转换
  if (state.formData.entName.length > 0) {
    return
  }
  let data = (await getZhCNAndPinyin(text, 50)) as any
  state.formData.entName = data.data.zhCN
  //如果英文字段为空，默认为拼音
  if (state.formData.enName.length == 0) {
    state.formData.enName = data.data.pinyin
  }
  if (state.formData.tableName.length == 0) {
    state.formData.tableName = 't_' + state.formData.enName.replaceAll(' ', '_')
  }
  formRef.value.clearValidate(['entName', 'tableName'])
}

//渲染页面的接口
const init = async () => {
  const id = currentRoute.value.query.id as string
  state.deleteIds = []
  state.formData.cols = []
  state.formData.indexes = []
  //修改
  if (id) {
    const data = (await getEntity(id)) as any
    state.formData = data.data
    //将日志选项值按位拆开到数组
    const value = state.formData.genLog
    state.logValues = []
    if ((value & 1) > 0) {
      state.logValues.push(1)
    }
    if ((value & 2) > 0) {
      state.logValues.push(2)
    }
    if ((value & 4) > 0) {
      state.logValues.push(4)
    }
    refreshDsList(state.formData.moduleId)
  } else {
    addFixedRow()
    const moduleId = currentRoute.value.query.moduleId as string
    if (moduleId) {
      state.formData.moduleId = moduleId
      refreshDsList(moduleId)
    }
  }
  const fromPath = currentRoute.value.query.fromPath as string
  state.fromPath = fromPath ? fromPath : '/Develop/EntityManage'
}
</script>

<template>
  <div>
    <!-- 卡片表頭 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>{{ $t('entity.edit') }}</span>
        </div>
      </template>
      <el-form
        ref="formRef"
        :model="state.formData"
        :rules="state.formRules"
        class="demo-form-inline"
        label-position="left"
        label-width="150px"
        style="padding-top: 10px"
      >
        <el-row :gutter="40">
          <el-col :xs="24" :sm="24" :md="12">
            <el-form-item :label="$t('orderNo.module')" prop="moduleId">
              <el-select
                v-model="state.formData.moduleId"
                :placeholder="$t('common.selectText')"
                size="default"
                @change="refreshDsList($event)"
              >
                <el-option
                  v-for="item in state.moduleList"
                  :key="item['moduleId']"
                  :label="item[state.modNameField]"
                  :value="item['moduleId']"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('entity.name')" prop="entName">
              <el-input
                v-model="state.formData.entName"
                :placeholder="$t('common.inputText') + $t('entity.name')"
                maxlength="30"
                show-word-limit
                @blur="zhHKAndPinyin($event)"
              />
            </el-form-item>
            <el-form-item :label="$t('common.hkName')" prop="hkName">
              <el-input
                v-model="state.formData.hkName"
                :placeholder="$t('common.inputText') + $t('common.hkName')"
                maxlength="30"
                show-word-limit
                @blur="zhCNAndPinyin($event)"
              />
            </el-form-item>
            <el-form-item :label="$t('common.enName')" prop="enName">
              <el-input
                v-model="state.formData.enName"
                :placeholder="$t('common.inputText') + $t('common.enName')"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
            <el-form-item
              :label="$t('entity.genLog')"
              prop="logValues"
              v-if="state.formData.isFromDb != 1"
            >
              <el-checkbox-group v-model="state.logValues">
                <el-checkbox v-for="item in state.logOptions" :key="item.id" :label="item.id">{{
                  item.name
                }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item
              :label="$t('common.updateBy')"
              prop="updateBy"
              v-if="state.formData.entId"
            >
              <el-input v-model="state.formData.updateBy" disabled />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12">
            <el-form-item :label="$t('entity.dataSource')" prop="dsId">
              <el-select
                v-model="state.formData.dsId"
                :placeholder="$t('common.selectText')"
                size="default"
              >
                <el-option
                  v-for="item in state.dsList"
                  :key="item['dsId']"
                  :label="item['dsName']"
                  :value="item['dsId']"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('entity.tableName')" prop="tableName">
              <el-input
                v-model="state.formData.tableName"
                :placeholder="$t('common.inputText') + $t('entity.tableName')"
                maxlength="50"
                show-word-limit
                :disabled="state.formData.isFromDb == 1"
                @blur="checkName($event)"
              />
            </el-form-item>
            <el-row v-if="state.formData.isFromDb != 1">
              <el-col :span="8">
                <el-form-item :label="$t('entity.genDb')" prop="isGenDb">
                  <el-switch
                    v-model.number="state.formData.isGenDb"
                    :active-value="1"
                    :inactive-value="0"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="6">
                <el-form-item :label="$t('entity.logicDel')" prop="isLogicDel" label-width="80px">
                  <el-switch
                    v-model.number="state.formData.isLogicDel"
                    :active-value="1"
                    :inactive-value="0"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item :label="$t('common.remark')" prop="remark">
              <el-input v-model="state.formData.remark" maxlength="100" show-word-limit />
            </el-form-item>
            <el-form-item :label="$t('common.status')" prop="status">
              <el-input
                v-if="state.formData.status == 1"
                :model-value="$t('entity.status1')"
                :disabled="true"
              />
              <el-input v-else :model-value="$t('entity.status0')" :disabled="true" />
            </el-form-item>
            <el-form-item
              :label="$t('common.updateTime')"
              prop="updateTime"
              v-if="state.formData.entId"
            >
              <el-input v-model="state.formData.updateTime" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="margin: 10px 0">
        <el-row>
          <el-col :span="8" style="font-size: 13px; color: orange"
            ><span v-if="state.formData.isFromDb == 1"
              ><Icon icon="ic:outline-tips-and-updates" /> &nbsp;{{ $t('entity.reverseTip') }}</span
            >
          </el-col>
          <el-col :span="16" style="text-align: right"
            ><el-button
              size="small"
              type="info"
              plain
              @click="state.dialogVisible = true"
              v-if="state.formData.entId && state.formData.isFromDb != 1"
            >
              <Icon icon="dashicons:index-card" />
              <span>{{ t('entity.indexes') }}</span></el-button
            >
            <el-button type="primary" size="small" plain @click="addFiveRow()">
              <Icon icon="icon-park-outline:five-key" />
              <span>{{ t('entity.add5') }}</span></el-button
            >
            <el-button type="success" size="small" plain @click="addRow()">
              <Icon icon="material-symbols:add-circle-rounded" />
              <span>{{ t('entity.add') }}</span></el-button
            ></el-col
          >
        </el-row>
      </div>
      <!-- 子表控件 -->
      <el-scrollbar>
        <div>
          <el-table
            :data="state.formData.cols"
            tooltip-effect="light"
            style="width: 100%; border-color: #a0cfff; font-size: 12px"
            stripe
            default-expand-all
            border
            size="small"
            :default-sort="{ prop: 'colOrder', order: 'ascending' }"
            :header-cell-style="{
              background: 'var(--el-color-primary-light-9)',
              color: '#409eff'
            }"
          >
            <el-table-column type="index" width="35" fixed>
              <template #header>
                <div style="margin-bottom: -10px">
                  <Icon
                    icon="ant-design:field-number-outlined"
                    size="24"
                    :title="$t('common.number')"
                /></div>
              </template>
            </el-table-column>
            <el-table-column
              prop="fieldName"
              :label="'*' + $t('entity.fieldName')"
              min-width="105"
              fixed
            >
              <template #default="scope">
                <el-input
                  v-model="scope.row.fieldName"
                  :maxlength="64"
                  :disabled="scope.row.isBuildIn == 1"
                />
              </template>
            </el-table-column>
            <el-table-column prop="showName" :label="'*' + $t('entity.showName')" min-width="110">
              <template #default="scope">
                <el-input
                  v-model="scope.row.showName"
                  :maxlength="50"
                  @blur="inputCnText($event, scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="hkName" :label="$t('dataDict.hkText')" min-width="110">
              <template #default="scope">
                <el-input
                  v-model="scope.row.hkName"
                  :maxlength="50"
                  @blur="inputHkText($event, scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="enName" :label="$t('dataDict.enText')" min-width="110">
              <template #default="scope">
                <el-input v-model="scope.row.enName" :maxlength="50" />
              </template>
            </el-table-column>
            <el-table-column prop="colType" :label="'*' + $t('entity.colType')" width="110">
              <template #default="scope">
                <el-select
                  v-model="scope.row.colType"
                  size="default"
                  :disabled="scope.row.isBuildIn == 1"
                  @change="changDataType(scope.row)"
                >
                  <el-option
                    v-for="item in state.dataTypes"
                    :key="item['value']"
                    :label="item['name']"
                    :value="item['value']"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="colLength" :label="$t('entity.colLength')" width="95">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.colLength"
                  :min="1"
                  :max="500"
                  :step="5"
                  size="small"
                  style="width: 100%"
                  controls-position="right"
                  :disabled="
                    scope.row.isBuildIn == 1 ||
                    !(scope.row.colType == 'decimal' || scope.row.colType == 'varchar')
                  "
                />
              </template>
            </el-table-column>
            <el-table-column prop="colPrec" :label="$t('entity.colPrec')" width="80">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.colPrec"
                  :min="0"
                  :max="15"
                  size="small"
                  style="width: 100%"
                  controls-position="right"
                  :disabled="scope.row.isBuildIn == 1 || scope.row.colType != 'decimal'"
                />
              </template>
            </el-table-column>
            <el-table-column prop="defaultVal" :label="$t('entity.defautVal')" min-width="65">
              <template #default="scope">
                <el-input v-model="scope.row.defaultVal" :disabled="scope.row.isBuildIn == 1" />
              </template>
            </el-table-column>
            <el-table-column prop="controlType" :label="$t('controlType.title')" width="110">
              <template #default="scope">
                <el-select
                  v-model="scope.row.controlType"
                  :placeholder="$t('common.selectText')"
                  size="default"
                  :disabled="scope.row.isBuildIn == 1"
                  @change="controlTypeChange(scope.row)"
                >
                  <el-option
                    v-for="item in state.controlTypes"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              prop="colOrder"
              align="right"
              :label="$t('common.sort')"
              width="70"
              sortable
            >
              <template #default="scope">
                <el-input
                  v-model.number="scope.row.colOrder"
                  :maxlength="9"
                  type="number"
                  :input-style="{ 'text-align': 'right' }"
                />
              </template>
            </el-table-column>
            <el-table-column prop="refEntId" :label="$t('entity.refEnt')" width="110">
              <template #default="scope">
                <div @dblclick="dblClickSelectEnt(scope.row)">
                  <el-input
                    v-model="scope.row[state.entityNameField]"
                    type="text"
                    clearable
                    v-show="scope.row.colLength >= 64 && scope.row.isBuildIn != 1"
                    :title="$t('entity.refEntityTip')"
                    :placeholder="$t('common.dbClickSelect')"
                    @clear="clearEnt(scope.row)"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="dictId" :label="$t('controlType.dictionary')" width="110">
              <template #default="scope">
                <div @dblclick="dblClickSelectDict(scope.row)">
                  <el-input
                    v-model="scope.row[state.dictNameField]"
                    type="text"
                    clearable
                    v-show="scope.row.colLength >= 10 && scope.row.isBuildIn != 1"
                    :title="$t('common.dbClickSelect')"
                    :placeholder="$t('common.dbClickSelect')"
                    @clear="clearDict(scope.row)"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="refSerialNoName" :label="$t('entity.autoNo')" width="110">
              <template #default="scope">
                <div @dblclick="dblClickSelectNo(scope.row)">
                  <el-input
                    v-model="scope.row[state.orderNoField]"
                    type="text"
                    clearable
                    v-show="scope.row.colLength >= 10 && scope.row.isBuildIn != 1"
                    :title="$t('common.dbClickSelect')"
                    :placeholder="$t('common.dbClickSelect')"
                    @clear="clearNo(scope.row)"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="isRequired" :label="$t('entity.required')" width="58">
              <template #default="scope">
                <el-switch
                  v-model.number="scope.row.isRequired"
                  :active-value="1"
                  :inactive-value="0"
                  :disabled="scope.row.isBuildIn == 1"
                />
              </template>
            </el-table-column>
            <el-table-column prop="isHide" :label="$t('entity.hide')" width="58">
              <template #default="scope">
                <el-switch
                  v-model.number="scope.row.isHide"
                  :active-value="1"
                  :inactive-value="0"
                  :disabled="scope.row.isBuildIn == 1"
                />
              </template>
            </el-table-column>
            <el-table-column prop="isUnique" :label="$t('entity.unique')" width="58">
              <template #default="scope">
                <el-switch
                  v-model.number="scope.row.isUnique"
                  :active-value="1"
                  :inactive-value="0"
                  :disabled="scope.row.isBuildIn == 1"
                />
              </template>
            </el-table-column>
            <el-table-column prop="canSearch" :label="$t('entity.canSearch')" width="58">
              <template #default="scope">
                <el-switch
                  v-model.number="scope.row.canSearch"
                  :active-value="1"
                  :inactive-value="0"
                  :disabled="scope.row.isBuildIn == 1"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="mainCol"
              :label="$t('entity.mainCol')"
              width="58"
              :title="$t('entity.mainColTip')"
            >
              <template #default="scope">
                <el-switch
                  v-model.number="scope.row.mainCol"
                  :active-value="1"
                  :inactive-value="0"
                  :disabled="scope.row.isBuildIn == 1"
                />
              </template>
            </el-table-column>
            <el-table-column prop="remark" :label="$t('common.remark')" min-width="170">
              <template #default="scope">
                <el-input v-model="scope.row.remark" :maxlength="50" />
              </template>
            </el-table-column>
            <el-table-column
              prop="op"
              align="center"
              :label="$t('common.operation')"
              width="50"
              fixed="right"
            >
              <template #default="scope">
                <el-button
                  type="danger"
                  size="small"
                  plain
                  circle
                  :title="$t('common.delete')"
                  v-if="scope.row.isBuildIn != 1"
                  @click="deleteRow(scope.row)"
                >
                  <el-icon>
                    <Delete />
                  </el-icon>
                </el-button>
              </template>
            </el-table-column>
          </el-table> </div
      ></el-scrollbar>
      <div class="detailFooter">
        <el-button
          type="primary"
          plain
          @click="save()"
          :loading="state.loading"
          v-if="state.formData.isBuildIn != 1"
        >
          <el-icon><Check /></el-icon>&nbsp;{{ $t('common.save') }}
        </el-button>
        <el-button
          type="success"
          plain
          :loading="state.publishLoading"
          @click="publish()"
          v-if="state.formData.entId && state.formData.status != 4 && state.formData.isBuildIn == 0"
          :title="$t('entity.publishBtnTip')"
        >
          <Icon icon="fluent:database-arrow-up-20-filled" />&nbsp;<span
            v-if="state.formData.status == 0"
            >{{ $t('entity.publish') }}</span
          ><span v-if="state.formData.status == 1">{{ $t('entity.rePublish') }}</span>
        </el-button>
        <el-button type="info" plain @click="goBack">
          <el-icon><Close /></el-icon>&nbsp;{{ $t('form.close') }}
        </el-button>
      </div>
    </el-card>
    <!-- 索引管理弹框 -->
    <el-dialog v-model="state.dialogVisible" :title="$t('entity.indexes')" width="800px" draggable>
      <el-form :model="state.dialogForm" :rules="state.dialogRule" label-width="auto">
        <el-row :gutter="20">
          <el-col :span="14">
            <el-form-item :label="$t('entity.fields')" prop="fields">
              <el-select-v2
                v-model="state.dialogForm.fields"
                :placeholder="$t('common.selectText')"
                style="position: relative; left: 10px; width: 100%; font-size: 12px"
                multiple
                :options="getIndexFields()"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('entity.unique')" prop="isUnique">
              <el-switch
                v-model.number="state.dialogForm.isUnique"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button @click="addIndex()" type="primary" size="small" plain>
              <Icon icon="material-symbols:add-circle-rounded" />
              <span> {{ $t('entity.addIndex') }}</span></el-button
            >
          </el-col>
        </el-row>
      </el-form>
      <!-- 索引列表 -->
      <el-scrollbar style="margin-top: 10px">
        <div>
          <el-table
            :data="state.formData.indexes"
            tooltip-effect="light"
            style="width: 100%; border-color: #a0cfff; font-size: 12px"
            stripe
            border
            size="small"
            :header-cell-style="{
              background: 'var(--el-color-primary-light-9)',
              color: '#409eff'
            }"
          >
            <el-table-column type="index" min-width="60">
              <template #header>
                <div style="margin-bottom: -10px">
                  <Icon
                    icon="ant-design:field-number-outlined"
                    size="24"
                    :title="$t('common.number')"
                /></div>
              </template>
            </el-table-column>
            <el-table-column
              prop="indexName"
              :label="$t('entity.indexName')"
              show-overflow-tooltip
              min-width="150"
            />
            <el-table-column
              prop="fields"
              :label="$t('entity.fields')"
              show-overflow-tooltip
              min-width="180"
            />
            <el-table-column prop="isUnique" :label="$t('entity.unique')" min-width="80">
              <template #default="{ row }">
                <span v-if="row.isUnique == 1">{{ $t('common.yes') }}</span>
                <span v-else>{{ $t('common.no') }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" :label="$t('common.status')" min-width="80">
              <template #default="{ row }">
                <span>{{ $t('entity.status' + row.status) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" :label="$t('common.createTime')" min-width="120" />
            <el-table-column
              fixed="right"
              :label="$t('common.operation')"
              width="80"
              align="center"
            >
              <template #default="{ row }">
                <el-button
                  type="danger"
                  plain
                  circle
                  size="small"
                  :title="$t('common.delete')"
                  v-if="row.status != 4"
                  @click="delIndex(row)"
                >
                  <el-icon>
                    <Delete />
                  </el-icon>
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer" style="text-align: center">
          <el-button @click="state.dialogVisible = false" plain type="info">
            <Icon icon="ri:arrow-go-back-fill" />
            <span> {{ $t('common.back') }}</span>
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 自动编号选择对话框 -->
    <SerialNoDialog
      v-model="state.serialNoDialogVisible"
      @selected="selectNo"
      @cancel="state.serialNoDialogVisible = false"
      width="850px"
    />
    <!-- 自动编号选择对话框 -->
    <DictSelectDialog
      v-model="state.dictSelectDialogVisible"
      @selected="selectDict"
      @cancel="state.dictSelectDialogVisible = false"
      width="850px"
    />
    <!-- 选择引用实体选择对话框 -->
    <EntityDialog
      v-model="state.entityDialogVisible"
      @selected="selectRefEnt"
      :module-id="state.formData.moduleId"
      :ent-id="state.formData.entId"
      @cancel="state.entityDialogVisible = false"
      width="850px"
    />
  </div>
</template>
<style lang="less" scoped>
.box-card {
  .card-header {
    font-size: 16px;
    letter-spacing: 1px;
  }
  :deep(.el-input) {
    font-size: 12px;
  }
  :deep(.el-textarea__inner) {
    height: 85px;
    font-size: 12px;
  }
}
:deep(.el-input__inner) {
  &::placeholder {
    font-size: 12px;
  }
}
.el-select-dropdown__item {
  font-size: 12px;
}
input {
  height: 28px;
  border: 1px solid #ddd;
  padding: 5px;
  width: 100%;
}
.required {
  color: red;
}
.inputRequired {
  width: 90%;
  margin-left: 3px;
}
</style>
